package com.gaogzhen.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author Administrator
 * @version 1.0
 * @description 当前登录用户
 * @date 2022-07-26 11:09
 */
public class CurrentUser {
    /**
     * 通过安全上下文获取用户Id
     * @return
     */
    public static Long getCurrentUserId() {
        // 从安全的上下文里面获取用户的ud
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null){
            // userId ->Long  anonymousUser
            String s = authentication.getPrincipal().toString();
            if("anonymousUser".equals(s)){
                //是因为用户没有登录访问时,就是这个用户
                return null ;
            }
            return Long.valueOf(s) ;
        }
        return null ;
    }
}
